package cn.shuangze.assetsms.view;

import cn.shuangze.assetsms.component.CalendarPanel;
import cn.shuangze.assetsms.dao.AssetsInfoDao;
import cn.shuangze.assetsms.dao.AssetsTypeDao;
import cn.shuangze.assetsms.dao.impl.AssetsInfoDaoJDBCImpl;
import cn.shuangze.assetsms.dao.impl.AssetsTypeDaoJDBCImpl;
import cn.shuangze.assetsms.entity.AssetsInfo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class AddAssetsInfo extends JDialog implements ActionListener {

    //定义DAO
    private AssetsTypeDao assetsTypeDao;
    private AssetsInfoDao assetsInfoDao;
    private String[][] comboValue;
    private Thread showThread;

    //定义所用的面板
    private JPanel westPanel = new JPanel();
    private JPanel eastPanel = new JPanel();
    private JPanel southPanel = new JPanel();
    private JPanel centerPanel = new JPanel();

    //框架的大小
    private Dimension faceSize = new Dimension(400, 400);
    private Font font = new Font("Dialog", 0, 12);

    //定义图形界面元素
    private JLabel[] jLabel = new JLabel[6];
    private JTextField[] jTextField = new JTextField[6];
    private JComboBox<String> jComboBox = new JComboBox<>();
    private JLabel nullLabel = new JLabel(" ");
    private JButton addBtn = new JButton("增加",new ImageIcon("images\\save.png"));
    private JButton clearBtn = new JButton("重置",new ImageIcon("images\\delete.png"));

    //定义日期选择日历
    private CalendarPanel calendarPanel = CalendarPanel.getInstance("yyyy-MM-dd");


    public AddAssetsInfo() {

        assetsTypeDao = new AssetsTypeDaoJDBCImpl();
        assetsInfoDao = new AssetsInfoDaoJDBCImpl();

        showThread = new Thread(() -> {
            try {
                showComboData();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "窗口初始化错误，错误原因：" + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        //界面初始化
        init();

    }


    private void init() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());

        westPanel.setLayout(new GridLayout(6, 1, 0, 12));
        centerPanel.setLayout(new GridLayout(6, 1, 0, 12));

        this.setModal(true);
        this.setSize(faceSize);

        //设置标题
        this.setTitle("资产增加");
        this.setResizable(false);

        //设置运行时窗口的位置
        this.setLocationRelativeTo(null);

        for (int i = 0; i < jLabel.length; i++) {
            jLabel[i] = new JLabel();
            jLabel[i].setFont(font);
            westPanel.add(jLabel[i]);
        }

        jLabel[0].setText("   资产名称   ");
        jLabel[1].setText("   资产类型   ");
        jLabel[2].setText("   资产型号   ");
        jLabel[3].setText("   资产价格   ");
        jLabel[4].setText("   购买日期   ");
        jLabel[5].setText("   备   注   ");

        for (int i = 0; i < jTextField.length; i++) {
            jTextField[i] = new JTextField();
            jTextField[i].setColumns(15);
        }
        calendarPanel.register(jTextField[4]);

        for (int i = 0; i < jTextField.length; i++) {
            if (i == 1) {
                jComboBox.setFont(font);
                centerPanel.add(jComboBox);
            } else {
                centerPanel.add(jTextField[i]);
            }
        }

        //启动显示
        showThread.start();

        addBtn.setFont(font);
        clearBtn.setFont(font);
        southPanel.add(addBtn);
        southPanel.add(clearBtn);
        eastPanel.add(nullLabel);

        contentPane.add(nullLabel, BorderLayout.NORTH);
        contentPane.add(westPanel, BorderLayout.WEST);
        contentPane.add(centerPanel, BorderLayout.CENTER);
        contentPane.add(southPanel, BorderLayout.SOUTH);
        contentPane.add(eastPanel, BorderLayout.EAST);

        //日期输入框处理
        jTextField[4].setEditable(false);
        jTextField[4].setBackground(new Color(0xFFFFFF));
        jTextField[4].setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        //添加事件
        addBtn.addActionListener(this);
        clearBtn.addActionListener(this);
        jTextField[3].addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                char keyChar = e.getKeyChar();
                if (!(keyChar >= '0' && keyChar <= '9')) {
                    e.consume();
                }
            }
        });
    }


    private void showComboData() throws Exception {
        comboValue = assetsTypeDao.findAll();
        jComboBox.removeAllItems();

        if (comboValue == null) {
            comboValue = new String[1][3];
            System.out.println("没有资产类别，请添加类别");
        }

        for (String[] strings : comboValue) {
            jComboBox.addItem("大类:" + strings[1] + " , 小类:" + strings[2]);
        }

    }

    private void setDefaultStatus() {
        for (JTextField j : jTextField) {
            j.setText(null);
        }

        jTextField[4].setText(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }


    @Override
    public void actionPerformed(ActionEvent e) {

        Object obj = e.getSource();

        if (obj == addBtn) {

            try {

                String name = jTextField[0].getText();
                int typeId = Integer.parseInt(comboValue[jComboBox.getSelectedIndex()][0]);
                String model = jTextField[2].getText();
                String price = jTextField[3].getText();
                java.sql.Date buyDate = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(jTextField[4].getText()).getTime());
                String other = jTextField[5].getText();
                String status = "可用";

                if (name.equals("")) {

                    JOptionPane.showMessageDialog(this, "名称不能为空！",
                            "添加失败", JOptionPane.WARNING_MESSAGE);
                    return;

                } else if (model.equals("")) {

                    JOptionPane.showMessageDialog(this, "型号不能为空！",
                            "添加失败", JOptionPane.WARNING_MESSAGE);
                    return;

                } else if (price.equals("")) {

                    JOptionPane.showMessageDialog(this, "价格不能为空！",
                            "添加失败", JOptionPane.WARNING_MESSAGE);
                    return;

                } else {

                    assetsInfoDao.add(new AssetsInfo(name, typeId, model, price, buyDate, status, other));

                    JOptionPane.showMessageDialog(this, "资产添加成功！",
                            "添加成功", JOptionPane.INFORMATION_MESSAGE);

                    setDefaultStatus();
                }



            } catch (Exception ex) {

                JOptionPane.showMessageDialog(this, "数据库访问错误，错误原因：" + ex.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }

        } else if (obj == clearBtn) {

            setDefaultStatus();

        }
    }

}
